<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const allRights = [
        {
          name: "sys",
          text: "系统管理",
          children: [
            { name: "sys.role", text: "角色管理" },
            { name: "sys.menu", text: "菜单管理" },
          ],
        },
        {
          name: "dashboard",
          text: "Dashboard",
          children: [
            { name: "dashboard.console", text: "主控台" },
            { name: "dashboard.workplace", text: "工作台" },
            { name: "dashboard.monitor", text: "监控页" },
          ],
        },
        {
          name: "setting",
          text: "设置页面",
          children: [
            { name: "setting.account", text: "个人设置" },
            { name: "setting.system", text: "系统设置" },
          ],
        },
      ];

      const curRights = ["sys", "sys.menu"];

      /**
       * 获取当前用户有权限的 Tree 型结构数据
       * @param {Array} list          全量权限的 Tree 型结构数据
       * @param {Array} permissions   当前用户的权限数据
       * @returns Array
       */
      function genRights(list, permissions) {
        // TODO...
        return list
          .filter((item) => permissions.includes(item.name))
          .map((item) => {
            // 为了避免修改到源数据，做一份浅拷贝
            const curItem = { ...item };

            // 取出 item.children ,将它作为 list 再次调用 genRights
            if (curItem.children) {
              const children = genRights(curItem.children, permissions);
              curItem.children = children;
            }

            return curItem;
          });
      }

      const value = genRights(allRights, curRights);
      console.log(value);
      console.log("allRights", allRights);
    </script>
  </body>
</html>
